﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;
using System.Diagnostics;

namespace FileConvertPdfSystemWebService
{
    /// <summary>
    /// Service1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/", Name = "ConvertFiletoPdf"),]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        List<int> intList = new List<int>();
        List<int> intListPower = new List<int>();
        List<int> intListWord = new List<int>();


        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }


        [WebMethod(CacheDuration = 60)]
        public bool str(string sourcePath, string targetPath)
        {
            bool s;
            recordexcelid();
            s = convert1(sourcePath, targetPath);
            killexcel1();
            return s;
        }
        [WebMethod(CacheDuration = 60)]
        public bool str1(string sourcePath, string targetPath)
        {
            bool s;
            recordpowerpointlid();
            s = convert(sourcePath, targetPath);
            killpowerpoint();
            return s;
        }
        [WebMethod(CacheDuration = 60)]
        public bool str2(string sourcePath, string targetPath)
        {
            bool s;
            recordwordlid();
            s = Convert3(sourcePath, targetPath);
            killword();
            return s;
        }


        [WebMethod(CacheDuration = 60)]
        public bool killexcel()
        {
            bool killexcelfalg = false;
            foreach (Process proc in System.Diagnostics.Process.GetProcesses())
            {
                int begpos;
                int endpos;

                string sProcName = proc.ToString();
                begpos = sProcName.IndexOf("(") + 1;
                endpos = sProcName.IndexOf(")");

                sProcName = sProcName.Substring(begpos, endpos - begpos);

                if (sProcName.ToLower().CompareTo("excel") == 0)
                {
                    try
                    {
                        killexcelfalg = true;
                        proc.Kill();
                    }
                    catch { }
                    break;
                }
            }
            return killexcelfalg;
        }

        private bool killexcel1()
        {
            bool killexcelfalg = false;
            foreach (Process proc in System.Diagnostics.Process.GetProcesses())
            {
                int begpos;
                int endpos;

                string sProcName = proc.ToString();
                begpos = sProcName.IndexOf("(") + 1;
                endpos = sProcName.IndexOf(")");

                sProcName = sProcName.Substring(begpos, endpos - begpos);

                if (sProcName.ToLower().CompareTo("excel") == 0)
                {
                    try
                    {
                        if (intList != null && intList.Count > 0)
                        {
                            bool bNewID = true;
                            foreach (int existed in intList)
                            {
                                if (existed == proc.Id)
                                {
                                    bNewID = false;
                                    break;
                                }
                            }
                            if (bNewID == true)
                            {
                                proc.Kill();
                            }
                        }
                        else
                        {
                            proc.Kill();
                        }
                        //killexcelfalg = true;
                    }
                    catch { }
                    break;
                }
            }
            return killexcelfalg;
        }
        private void recordexcelid()
        {
            intList.Clear();
            foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
            {
                if (p.ProcessName.ToUpper() == "EXCEL")
                {
                    intList.Add(p.Id);
                }
            }
        }
        /// <summary>
        /// execel to pdf
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="targetPath"></param>
        /// <returns></returns>
        private bool convert1(string sourcePath, string targetPath)
        {

            bool result;
            object missing = Type.Missing;
            Excel.ApplicationClass application = null;
            Excel.Workbook workBook = null;
            Excel.XlFixedFormatType excelType = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF;

            try
            {
                application = new Excel.ApplicationClass();
                object target = targetPath;
                object type = excelType;
                workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing,
                        missing, missing, missing, missing, missing, missing, missing, missing, missing);

                workBook.ExportAsFixedFormat(excelType, target, Excel.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);
                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (workBook != null)
                {
                    workBook.Close(true, missing, missing);
                    workBook = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }

        private bool killpowerpoint()
        {
            bool killexcelfalg = false;
            foreach (Process proc in System.Diagnostics.Process.GetProcesses())
            {
                int begpos;
                int endpos;

                string sProcName = proc.ToString();
                begpos = sProcName.IndexOf("(") + 1;
                endpos = sProcName.IndexOf(")");

                sProcName = sProcName.Substring(begpos, endpos - begpos);

                if (sProcName.ToLower().CompareTo("powerpnt") == 0)
                {
                    try
                    {
                        if (intListPower != null && intListPower.Count > 0)
                        {
                            bool bNewID = true;
                            foreach (int existed in intListPower)
                            {
                                if (existed == proc.Id)
                                {
                                    bNewID = false;
                                    break;
                                }
                            }
                            if (bNewID == true)
                            {
                                proc.Kill();
                            }
                        }
                        else
                        {
                            proc.Kill();
                        }
                        //killexcelfalg = true;
                    }
                    catch { }
                    break;
                }
            }
            return killexcelfalg;
        }
        private void recordpowerpointlid()
        {
            intList.Clear();
            foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
            {
                if (p.ProcessName.ToUpper() == "powerpnt")
                {
                    intListPower.Add(p.Id);
                }
            }
        }
        /// <summary>
        /// powerpoint to pdf
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="targetPath"></param>
        /// <returns></returns>
        private bool convert(string sourcePath, string targetPath)
        {
            bool result;
            object missing = Type.Missing;
            PowerPoint.ApplicationClass application = null;
            PowerPoint.Presentation persentation = null;
            PowerPoint.PpSaveAsFileType ppType = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF;
            try
            {
                application = new PowerPoint.ApplicationClass();
                persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
                persentation.SaveAs(targetPath, ppType, Microsoft.Office.Core.MsoTriState.msoTrue);

                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (persentation != null)
                {
                    persentation.Close();
                    persentation = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }


        private bool killword()
        {
            bool killexcelfalg = false;
            foreach (Process proc in System.Diagnostics.Process.GetProcesses())
            {
                int begpos;
                int endpos;

                string sProcName = proc.ToString();
                begpos = sProcName.IndexOf("(") + 1;
                endpos = sProcName.IndexOf(")");

                sProcName = sProcName.Substring(begpos, endpos - begpos);

                if (sProcName.ToLower().CompareTo("winword") == 0)
                {
                    try
                    {
                        if (intListWord != null && intListWord.Count > 0)
                        {
                            bool bNewID = true;
                            foreach (int existed in intListWord)
                            {
                                if (existed == proc.Id)
                                {
                                    bNewID = false;
                                    break;
                                }
                            }
                            if (bNewID == true)
                            {
                                proc.Kill();
                            }
                        }
                        else
                        {
                            proc.Kill();
                        }
                        //killexcelfalg = true;
                    }
                    catch { }
                    break;
                }
            }
            return killexcelfalg;
        }
        private void recordwordlid()
        {
            intList.Clear();
            foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
            {
                if (p.ProcessName.ToUpper() == "winword")
                {
                    intListWord.Add(p.Id);
                }
            }
        }
        /// <summary>
        /// word to pdf
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="targetPath"></param>
        /// <returns></returns>
        private bool Convert3(string sourcePath, string targetPath)
        {
            bool result;
            object paramMissing = Type.Missing;
            Word.ApplicationClass wordApplication = new Word.ApplicationClass();
            Word.Document wordDocument = null;
            Word.WdExportFormat wd = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;
            try
            {
                object paramSourceDocPath = sourcePath;
                string paramExportFilePath = targetPath;

                Word.WdExportFormat paramExportFormat = wd;
                bool paramOpenAfterExport = false;
                Word.WdExportOptimizeFor paramExportOptimizeFor =
                        Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
                Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument;
                int paramStartPage = 0;
                int paramEndPage = 0;
                Word.WdExportItem paramExportItem = Word.WdExportItem.wdExportDocumentContent;
                bool paramIncludeDocProps = true;
                bool paramKeepIRM = true;
                Word.WdExportCreateBookmarks paramCreateBookmarks =
                        Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
                bool paramDocStructureTags = true;
                bool paramBitmapMissingFonts = true;
                bool paramUseISO19005_1 = false;

                wordDocument = wordApplication.Documents.Open(
                        ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing);

                if (wordDocument != null)
                    wordDocument.ExportAsFixedFormat(paramExportFilePath,
                            paramExportFormat, paramOpenAfterExport,
                            paramExportOptimizeFor, paramExportRange, paramStartPage,
                            paramEndPage, paramExportItem, paramIncludeDocProps,
                            paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                            paramBitmapMissingFonts, paramUseISO19005_1,
                            ref paramMissing);
                result = true;
            }
            finally
            {
                if (wordDocument != null)
                {
                    wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordDocument = null;
                }
                if (wordApplication != null)
                {
                    wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordApplication = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }



    }
}